import React, { useLayoutEffect, useState } from 'react';
import DndContext from './context/DndContext';

import DragDropManagerImpl from './classes/DragDropManagerImpl';
import HandlerRegistryImpl from './classes/HandlerRegistryImpl';
import type { DragDropManager } from './classes/interface';
import store from './redux/store';

function createDragDropManager(): DragDropManager {
  // 注册表(监听器的一部分)
  const registry = new HandlerRegistryImpl();

  //管理器
  const manager = new DragDropManagerImpl(store, registry);

  return manager;
}

function HTML5DndProvider(props: { children: React.ReactElement }) {
  const { children } = props;
  const [dragDropManager, setDragDropManager] = useState<DragDropManager>();

  useLayoutEffect(() => {
    const dragDropManager = createDragDropManager();
    setDragDropManager(dragDropManager);
    return () => {
      if (dragDropManager) {
        dragDropManager.removeEventListeners();
      }
    };
  }, []);

  return (
    dragDropManager && (
      <DndContext.Provider value={{ dragDropManager }}>
        {children}
      </DndContext.Provider>
    )
  );
}

export default HTML5DndProvider;
